package training.framework.persistence;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

public abstract class AbstractManagerTemplate {
	public void execute(EntityManagerFactory factory) {
		EntityManager manager = null;
		EntityTransaction transaction = null;
		try {
			manager =  factory.createEntityManager();
			transaction = manager.getTransaction();
			transaction.begin();
			execute(manager);
			manager.flush();
			transaction.commit();
		} catch (RuntimeException e) {
			if (transaction != null) {
				try {
					transaction.rollback();
				} catch (RuntimeException nestedException) {} 
			}
			throw e;
		} finally {
			if (manager != null) {
				try {
					manager.close();
				} catch (RuntimeException e) {}
			}
		}				
	}

	protected abstract void execute(EntityManager manager);	
}
